<template>
	<jk-dialog
		v-model="showDialog"
		title="派工任务"
		width="1300px"
		:confirm-btn-loading="confirmBtnLoading"
		:show-confirm-btn="false"
		:show-cancel-btn="false"
		:show-close-btn="true"
		@on-close="onVisibleChange(false)"
		@on-cancel="onVisibleChange(false)"
		@on-visible-change="onVisibleChange"
	>
		<el-form
			ref="ruleForm"
			:model="ruleForm"
			:rules="rules"
			label-width="120px"
			:show-message="false"
			:hide-required-asterisk="true"
		>
			<div ref="box1">
				<el-tag type="primary" effect="plain" class="margin-bottom-4">
					<span class="el-icon-tickets item-gap"></span>
					<span>基本信息</span>
				</el-tag>
				<jk-card>
					<el-row class="flex-start-center-wrap">
						<el-col :span="8">
							<el-form-item class="margin-bottom-10" label="单据编号">
								<span class="read-only-2">{{ ruleForm.code || '系统自动生成' }}</span>
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item class="margin-bottom-10" label="派工日期" prop="belongDate">
								<span class="read-only-2">{{ ruleForm.belongDate }}</span>
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item class="margin-bottom-10" label="预计完成日期" prop="planCompletionTime">
								<span class="read-only-2">{{ ruleForm.planCompletionTime }}</span>
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item class="margin-bottom-10" label="保养类别">
								<span class="read-only-2">{{ ruleForm.upkeepTypeList ? ruleForm.upkeepTypeList.map(x => x.name).join() : '' }}</span>
							</el-form-item>
						</el-col>
						<el-col :span="24">
							<el-form-item class="margin-bottom-0" label="备注">
								<span class="read-only-2">{{ ruleForm.remark }}</span>
							</el-form-item>
						</el-col>
					</el-row>
				</jk-card>
			</div>
			<div ref="box2" class="flex-start-center margin-bottom-4 margin-top-10" style="align-items: flex-end; justify-content: space-between;">
				<el-tag size="mini" type="primary">
					<span class="el-icon-s-order item-gap"></span>
					<span>设备及项目清单</span>
				</el-tag>
				<div style="display: flex; align-items: center">
					<el-popconfirm
						title="确定全部完成吗？"
						@confirm="onOverBut"
					>
						<el-button slot="reference" size="small" :disabled="buttonState === 2">全部完成</el-button>
					</el-popconfirm>
					<el-button size="small" class="margin-left-4" :disabled="leftButtonState.every(x => x === 3)" @click="onUpkeepDispatchPlan">全部忽略</el-button>
					<el-select v-model="upkeepItemName" placeholder="检验类型" style="width: 150px" size="small" class="margin-left-4 search-bar-item-size1 item-gap" @change="onUpkeepItemChange">
						<el-option
							v-for="item in upkeepItemNameList"
							:key="item.name"
							:label="item.name"
							:value="item.name"
						>
						</el-option>
					</el-select>
					<jk-search-button @click="onSearchBtn"></jk-search-button>
				</div>
			</div>
			<jk-table border :data="ruleForm.machineList || []" :height="dialogTableHeight - 20">
				<vxe-column title="设备名称" align="left" field="machineName" :width="70" />
				<vxe-column title="保养项目及人员" align="left" field="belongDate" :min-width="110">
					<template slot="header">
						<div class="flex-start-center width-100-percent">
							<div style="width: 50px;text-align: center;">序号</div>
							<div style="width: 110px;">项目名称</div>
							<div style="width: 90px;text-align: center;">状态</div>
							<div style="width: 150px;">计划保养时间</div>
							<div style="width: 150px;">保养情况</div>
							<div style="width: 180px;">保养实际开始时间</div>
							<!--<div style="width: 150px;">上次保养时间</div>-->
							<div style="min-width:180px;flex-grow: 1">人员</div>
							<div style="width: 110px;text-align: center;">操作</div>
						</div>
					</template>
					<template slot-scope="scope">
						<upkeep-order-machine-list
							:row="scope.row"
							:upkeep-item-list="scope.row.upkeepItemList || []"
							@on-finish="onUpdateStateBtn"
							@on-clear-finish="onClearBtn"
						></upkeep-order-machine-list>
					</template>
				</vxe-column>
				<vxe-column title="操作" align="center" field="operation" :width="112">
					<template slot-scope="scope">
						<div class="flex-center">
							<el-popconfirm
								v-if="scope.row.auditState !== 3"
								title="确定操作吗？"
								@confirm="onBatchFinishBtn(scope)"
							>
								<jk-button
									v-if="scope.row.auditState !== 3"
									slot="reference"
									:has-permission="getPermission(['machinemanager:upkeepDispatchPlan:update'])"
									size="mini"
									type="success"
									:disabled="scope.row.machineUpkeepState !== 0"
									icon="el-icon-finished"
								>批量完成</jk-button>
							</el-popconfirm>
							<el-popconfirm
								v-else
								title="确定操作吗？"
								@confirm="onBatchClearFinishBtn(scope)"
							>
								<jk-button
									v-if="scope.row.auditState === 3"
									slot="reference"
									:has-permission="getPermission(['machinemanager:upkeepDispatchPlan:update'])"
									size="mini"
									type="warning"
									icon="el-icon-circle-close"
								>批量撤销</jk-button>
							</el-popconfirm>
						</div>
					</template>
				</vxe-column>
			</jk-table>
		</el-form>
		<el-dialog
			width="30%"
			title="请选择日期"
			:visible.sync="showBelongTime"
			append-to-body
		>
			<el-form ref="ruleForm" :model="ruleForm" :rules="rules">
				<el-form-item label="延后日期" class="flex-center margin-5-0" prop="belongTime">
					<jk-date-picker v-model="ruleForm.belongTime" type="datetime" style="width: 100%;" placeholder="日期" size="medium"></jk-date-picker>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer flex-between-center-wrap">
				<div style="font-size: 12px; color: #f55151">友情提示：系统只处理未完成的项<br />已完成的项目将跳过不进行处理。</div>
				<div>
					<el-button size="small" @click="showBelongTime = false">取 消</el-button>
					<el-button size="small" type="primary" @click="onUpkeepDispatchPlanBun">确定 忽略</el-button>
				</div>
			</div>
		</el-dialog>
	</jk-dialog>
</template>

<script>
    import calHeight from '/src/mixins/cal-dialog-height';
    import selectUpkeepPlanDialog from './components/select-upkeep-plan-dialog';
    import {
        machineManagerUpkeepDispatchGet, machinemanagerUpkeepDispatchGetDetail,
        machineManagerUpkeepDispatchPlanBatchRevokeState,
        machineManagerUpkeepDispatchPlanBatchUpdateStateFinish,
        machinemanagerUpkeepDispatchPlanBatchIgnore,
        machineManagerUpkeepDispatchUpdate, machineManagerUpkeepDispatchCreate
    } from '../../../../api/machine/upkeepOrder';
    import upkeepOrderMachineList from './components/upkeepOrderMachineList/from-update-state';
    import { formatDate, tipsBar } from '../../../../utils/jk/jk-tool';
    import permissionMixin from '../../../../mixins/permission-mixin';
    export default {
        components: {
            upkeepOrderMachineList,
            selectUpkeepPlanDialog
        },
        props: {
            dialogState: {
                type: Boolean,
                default: false
            },
            pageType: {
                type: String,
                default: ''
            },
            formData: {
                type: Object,
                default() {
                    return {};
                }
            },
            dataId: {
                type: [String, Number],
                default: ''
            }
        },
        mixins: [calHeight, permissionMixin],
        data() {
            return {
                upkeepTypeList: [],
                upkeepItemNameList: [],
                processList: [],
                leftButtonState: [],
                showDialog: false,
                showBelongTime: false,
                confirmBtnLoading: false,
                upkeepItemName: '全部',
                ruleForm: {
                    'belongDate': '',
                    'code': '',
                    'machineList': [],
                    'remark': '',
                    'state': 0,
                    'upkeepTypeList': [],
                    'belongTime': ''
                },
                ids: [],
                rules: {
                    code: [{ required: true, trigger: 'change' }],
                    belongDate: [{ required: true, trigger: 'change' }],
                    belongTime: [{ required: true, trigger: 'change' }],
                    name: [{ required: true, trigger: 'change' }],
                    processId: [{ required: true, trigger: 'change' }],
                    cycleMax: [{ required: true, trigger: 'change' }],
                    cycleMin: [{ required: true, trigger: 'change' }]
                },
                rawMachine: [],
                machineIndex: null,
                upkeepIndex: null,
                buttonState: null
            };
        },
        methods: {
            onBatchClearFinishBtn(scope) {
                // 只处理已完成的
                const ids = scope.row.upkeepItemList.filter(x => x.upkeepState === 3).map(x => x.id);
                this.onClearBtn(ids);
            },
            onBatchFinishBtn(scope) {
                // 只处理未完成的
                const ids = scope.row.upkeepItemList.filter(x => x.upkeepState !== 3).map(x => x.id);
                this.onUpdateStateBtn(ids);
            },
            onClearBtn(ids) {
                machineManagerUpkeepDispatchPlanBatchRevokeState({ ids }).then(res => {
                    if (res.data.status === 200) {
                        tipsBar(this, 'save');
                        this.$emit('on-update');
                        this.getDetailRequest();
                    }
                });
            },
            onUpdateStateBtn(ids) {
                machineManagerUpkeepDispatchPlanBatchUpdateStateFinish({ ids }).then(res => {
                    if (res.data.status === 200) {
                        tipsBar(this, 'save');
                        this.$emit('on-update');
                        this.getDetailRequest();
                    }
                });
            },
            getParamData() {
                const params = JSON.parse(JSON.stringify(this.ruleForm));
                params.upkeepTypeList = params.upkeepTypeIds ? this.upkeepTypeList.filter(x => params.upkeepTypeIds.includes(x.id)) : [];
                return params;
            },
            onVisibleChange(e) {
                this.$emit('on-visible-change', e);
                if (!e) {
                    Object.assign(this.$data, this.$options.data());
                    this.$nextTick(() => {
                        this.$refs.ruleForm.resetFields();
                    });
                }
            },
            getDetailRequest() {
                return machineManagerUpkeepDispatchGet({ id: this.dataId }).then(res => {
                    if (res.data.status === 200) {
                        const resData = res.data.res || {};
                        this.ruleForm = resData;
                        let hasChecked = false;
                        resData.machineList.forEach(x => {
                            x.upkeepItemList.forEach(item => {
                                this.leftButtonState.push(item.upkeepState);
                            });
                            if (x.upkeepItemList.some(y => y.upkeepState === 2)) {
                                hasChecked = true;
                                return;
                            }
                        });
                        this.buttonState = hasChecked ? 1 : 2;
                    }
                });
            },
            getUpkeepItemNameList() {
                const firstItem = { name: '全部' };
                this.upkeepItemNameList = this.ruleForm.upkeepItemNameList.map(task => ({ name: task }));
                this.upkeepItemNameList.unshift(firstItem);
            },
            onUpkeepItemChange(e) {
                if (e === '全部') {
                    this.leftButtonState = [];
                    this.getDetailRequest();
                } else {
                    machinemanagerUpkeepDispatchGetDetail({ id: this.dataId, upkeepItemName: e }).then(res => {
                        if (res.data.status === 200) {
                            let hasChecked = false;
                            const resData = res.data.res ? JSON.parse(JSON.stringify(res.data.res)) : {};
                            this.leftButtonState = [];
                            resData.forEach(x => {
                                x.upkeepItemList.forEach(item => {
                                    this.leftButtonState.push(item.upkeepState);
                                });
                                if (x.upkeepItemList.some(y => y.upkeepState === 2)) {
                                    hasChecked = true;
                                    return;
                                }
                            });
                            this.buttonState = hasChecked ? 1 : 2;
                            this.ruleForm.machineList = resData;
                        }
                    });
                }
            },
            onSearchBtn() {
                machinemanagerUpkeepDispatchGetDetail({ id: this.dataId, upkeepItemName: this.upkeepItemName === '全部' ? '' : this.upkeepItemName }).then(res => {
                    if (res.data.status === 200) {
                        const resData = res.data.res ? JSON.parse(JSON.stringify(res.data.res)) : {};
                        this.ruleForm.machineList = resData;
                    }
                });
            },
            onOverBut() {
                const ids = this.ruleForm.machineList.reduce((acc, machine) => {
                    return acc.concat(machine.upkeepItemList.filter(x => x.upkeepState !== 3).map(item => item.id));
                }, []);
                machineManagerUpkeepDispatchPlanBatchUpdateStateFinish({ ids }).then(res => {
                    if (res.data.status === 200) {
                        this.showDialog = false;
                        tipsBar(this, 'save');
                        this.$emit('on-update');
                        this.$emit('on-visible-change', false);
                        this.getDetailRequest();
                    }
                });
            },
            onUpkeepDispatchPlan() {
                this.showBelongTime = true;
                this.ids = this.ruleForm.machineList.reduce((acc, machine) => {
                    return acc.concat(machine.upkeepItemList.filter(x => x.upkeepState !== 3).map(item => item.id));
                }, []);
            },
            onUpkeepDispatchPlanBun() {
                this.$refs['ruleForm'].validate(valid => {
                    if (valid) {
                        const params = {
                            ids: this.ids,
                            planUpkeepTime: this.ruleForm.belongTime
                        };
                        machinemanagerUpkeepDispatchPlanBatchIgnore(params).then(res => {
                            if (res.data.status === 200) {
                                this.showBelongTime = false;
                                this.showDialog = false;
                                this.$tipsBar(this, 'save');
                                this.$emit('on-update');
                            }
                        });
                    } else {
                        this.$tipsBar(this, 'validator');
                    }
                });
            },
            async getDependentData() {
                if (this.dataId) await this.getDetailRequest();
                await this.getUpkeepItemNameList();
            }
        },
        watch: {
            dialogState(newVal) {
                this.showDialog = newVal;
                if (newVal) {
                    this.getDependentData();
                }
            }
        }
    };
</script>
